
public class Leetcode1664 {
    public static void main(String[] args) {
        System.out.println(waysToMakeFair(new int[]{4, 1, 1, 2, 5, 1, 5, 4}));
        System.out.println(waysToMakeFair(new int[]{2, 1, 6, 4}));
        System.out.println(waysToMakeFair(new int[]{1, 1, 1}));
        System.out.println(waysToMakeFair(new int[]{1, 2, 3}));
    }

    public static int waysToMakeFair(int[] nums) {
        int[] lastOddNumberSum = new int[nums.length];
        int[] lastEvenNumberSum = new int[nums.length];

        for (int i = nums.length - 2; i >= 0; i--) {
            lastOddNumberSum[i] = lastEvenNumberSum[i + 1];
            lastEvenNumberSum[i] = lastOddNumberSum[i + 1] + nums[i + 1];
        }

        int oddNumberSum = lastEvenNumberSum[0];
        int evenNumberSum = lastOddNumberSum[0] + nums[0];

        int res = 0;
        for (int i = 0; i < nums.length; i++) {
            if (i % 2 == 0) {
                if (evenNumberSum - nums[i] - lastOddNumberSum[i] + lastEvenNumberSum[i] == oddNumberSum - lastEvenNumberSum[i] + lastOddNumberSum[i]) {
                    res++;
                }
            } else {
                if (evenNumberSum + lastOddNumberSum[i] - lastEvenNumberSum[i] == oddNumberSum - nums[i] + lastEvenNumberSum[i] - lastOddNumberSum[i]) {
                    res++;
                }
            }
        }

        return res;
    }
}
